﻿
using HuaJiLedger.Models.Ledger;
using HuaJiLedger.Repositorys;
using System.Collections.ObjectModel;

namespace HuaJiLedger.ViewModels.Home;

internal class LedgerItemDetailViewModel : ViewModelBase, IQueryAttributable
{
    private string id;
    private string inOut;
    private int type;
    private double money;
    private string dateTime;
    private string note;
    private readonly LedgerItemRepository repository;

    public string Id
    { get => id; set => SetProperty(ref id, value); }
    public string InOut
    { get => inOut; set => SetProperty(ref inOut, value); }
    public int Type
    { get => type; set => SetProperty(ref type, value); }
    public double Money
    { get => money; set => SetProperty(ref money, value); }
    public string DateTime
    { get => dateTime; set => SetProperty(ref dateTime, value); }
    public string Note
    { get => note; set => SetProperty(ref note, value); }

    public ObservableCollection<string> TypeItems { get; set; }

    public Command SaveEditCommand;

    public LedgerItemDetailViewModel(Page page)
    {
        this.page = page;

        repository = new LedgerItemRepository();
        TypeItems = new ObservableCollection<string>(LedgerData.LedgerItemTypeStrArr);

        SaveEditCommand = new Command(ActionSaveEditCommand);
    }

    async void SetData(string _id)
    {
        var ledgerItem = await repository.GetLedgerItemAsync(_id);
        InOut = ledgerItem.InOut.ToString();
        Type = (int)ledgerItem.Type;
        Money = ledgerItem.Money;
        DateTime = ledgerItem.DateTime;
        Note = ledgerItem.Note;
    }

    async void ActionSaveEditCommand()
    {
        var ledgerItem = new LedgerItem
        {
            Id = Id,
            DateTime = DateTime,
            Type = (LedgerItemType)Type,
            Money = Money,
            Note = Note,
            InOut = int.Parse(InOut)
        };

        if (await repository.UpdateLedgerItemAsync(ledgerItem) != 0)
        {
            await page.DisplayAlert("提示", "修改成功", "OK");
        }
    }

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        if (query.Count <= 0)
            return;

        if (query.TryGetValue("ID", out object _id))
        {
            Id = _id as string;
            SetData(Id);
        }
    }
}
